/*蛇体代码*/
(function (window) {


    //随机产生一个十六进制的颜色的函数.
    function getColorForRandom(){
        var arr = ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'];  //下标0-15
        var str = "#";
        //循环产生 6个 0-15的数.
        for(var i = 0 ; i < 6; i++){
            var num = Math.floor(Math.random()*16);
            //根据这个随机数,在arr数组中去取值.
            str += arr[num];
        }
        return str;
    }


    //保存蛇的每一节身体
    var list = [];
    function Snake(width,height,direction,br) {
        this.width = width || 20;
        this.height = height || 20;
        this.direction = direction || 'right';
        this.borderRadius = br || 10;

        this.body = [
            {x:3,y:1,bgColor:'red',borderRadius:7},
            {x:2,y:1,bgColor:'green',borderRadius:7},
            {x:1,y:1,bgColor:'pink',borderRadius:7}
        ]
    }

    Snake.prototype.render = function (map) {
        remove(map);//移除老蛇尾巴，在渲染新蛇之前
        for (var i = 0; i < this.body.length ; i++) {
            var unit = this.body[i];
            var div1 = document.createElement('div');
            div1.style.position = 'absolute';
            div1.style.left = unit.x * this.width + 'px';
            div1.style.top = unit.y * this.height + 'px';
            div1.style.width = this.width + 'px';
            div1.style.height = this.height + 'px';
            div1.style.borderRadius = this.borderRadius + 'px';
            div1.style.backgroundColor = unit.bgColor;
            map.appendChild(div1);
            //吧当前蛇身体放进list数组中
            list.push(div1);
        }

    };

    //删掉蛇
    function remove(map){
        for (var i = 0; i < list.length; i++) {
            map.removeChild(list[i])
        };
        list = [];
    }

    Snake.prototype.move = function (food) {
        for (var i = this.body.length - 1; i > 0 ; i--) {
            this.body[i].x = this.body[i-1].x;
            this.body[i].y = this.body[i-1].y;
        };
        //蛇头移动
        switch (this.direction) {
            case 'top':
                this.body[0].y--;
                break;
            case 'bottom':
                this.body[0].y++;
                break;
            case 'right':
                this.body[0].x++;
                break;
            case 'left':
                this.body[0].x--;
                break;
        }

        //判断蛇有没有吃掉食物
        var snakeHeadX = this.body[0].x * this.width;
        var snakeHeadY = this.body[0].y * this.height;
        var foodX = food.x;
        var foodY = food.y;
        var lastUnit = this.body[this.body.length - 1];

        if (snakeHeadX == foodX && snakeHeadY == foodY) {
            this.body.push({
                x:lastUnit.x,
                y:lastUnit.y,
                bgColor:getColorForRandom()
            });
            food.render(map);
        }
    };



    window.Snake = Snake;
}(window));